#include "sboxuser.h"


SBoxUser::SBoxUser(QString usr, QString psd, QString regmail = "")
{
    usrname = usr;
    pwd = psd;
    mail = regmail;
    con = new sqlConn(QCoreApplication::applicationDirPath()+"/settings/conf.ini");
    getUserID();
}

void SBoxUser::updateUser()
{
    con->connect();
    QSqlQuery query;
    query.prepare(QString("UPDATE userprofile SET usr = :usrname, pwd = :pwd, strPriv = :strPriv, mail = :mail WHERE id = ").append(id));
    query.addBindValue(":usrname", usrname);
    query.addBindValue(":pwd", pwd);
    query.addBindValue(":strPriv", strPriv);
    query.addBindValue(":mail", mail);
    query.exec();
    con->close();
}

void SBoxUser::generateID()
{
    const char Seed[1024] = "SBox";
    RandomPool RandPool;
    RandPool.IncorporateEntropy((byte *)Seed, strlen(Seed));

    //generate private key
    RSAES_OAEP_SHA_Decryptor Priv(RandPool, 2048);
    HexEncoder PrivateEncoder(new StringSink(strPriv)); /**/
    Priv.DEREncode(PrivateEncoder);
    PrivateEncoder.MessageEnd();

    //generate public key using private key
    RSAES_OAEP_SHA_Encryptor Pub(Priv);
    HexEncoder PublicEncoder(new StringSink(strPub));
    Pub.DEREncode(PublicEncoder);
    PublicEncoder.MessageEnd();

//    string digest;
//    Weak::MD5 md5;
//    StringSource(strPriv, true, new HashFilter(md5, new HexEncoder(new StringSink(digest))));
//    strPriv = digest;
}

void SBoxUser::createUser()
{
    con->connect();
    QSqlQuery query;
    query.prepare("INSERT INTO userprofile (usr, pwd, strPriv, mail) VALUES (:usrname, :pwd, :strPriv, :mail)");
    query.addBindValue(":usrname", usrname);
    query.addBindValue(":pwd", pwd);
    query.addBindValue(":strPriv", strPriv );
    query.addBindValue(":mail", mail);
    query.exec();
    con->close();
    getUserID();
    //write the strPub
    ofstream fs ;
    fs.open(QCoreApplication::applicationDirPath().append("/Users/").append(usrname).append(".pbk").toStdString());
    fs << strPub << endl;
    fs.close();
}

void SBoxUser::getUserID()
{
    con->connect();
    QString sqlstr = "SELECT id FROM userprofile WHERE usr = '";
    sqlstr.append(usrname).append("'");
    QSqlQuery* query = con->queryData(sqlstr);
    if(query->next())
        id = query->value(0).toString();
}
